import { debounce } from "lodash";
import { useEffect, useState } from "react";

/**
 *
 * @param {*} containerRef
 * @param {*} anchorItemsRef
 * @returns [string, function]
 */
export const useAnchor = (containerRef, anchorItemsRef) => {
	const [currentAnchor, setCurrentAnchor] = useState(null);
	// console.log(containerRef, "containerRef");
	useEffect(() => {
		const handleScroll = () => {
			// 获取容器相对于视口的位置信息
			const containerRect = containerRef.current.getBoundingClientRect();
			const containerTop = containerRect.top; // 容器顶部相对于视口顶部的距离
			const containerBottom = containerRect.bottom; // 容器底部相对于视口顶部的距离
			let scroll = containerRef.current.scrollTop; // 容器的滚动距离
			let closestDistance = Number.MAX_SAFE_INTEGER; // 最近的距离初始化为一个足够大的值
			let closestAnchor = null; // 最近的锚点初始化为空

			// 遍历所有锚点元素
			// console.log(Object.entries(anchorItemsRef.current), "Object.entries(anchorItemsRef.current)");

			Object.entries(anchorItemsRef.current).forEach(([key, el]) => {
				// 获取当前锚点元素相对于容器顶部的位置信息
				// if (!el) {
				//   el=
				// }
				if (!el) {
					findLastNonEmptyIdItem(Object.entries(anchorItemsRef.current));
				}
				const rect = el?.getBoundingClientRect();
				const elementTop = rect?.top - containerTop; // 元素顶部相对于容器顶部的距离
				const elementBottom = rect?.bottom - containerTop; // 元素底部相对于容器顶部的距离
				// console.log(containerTop, "containerTop");
				// 检查元素是否在容器内部部分可见
				if (elementBottom > 0 && elementTop < containerBottom) {
					// console.log(elementBottom, "elementBottom");
					// console.log(containerBottom, "containerBottom");
					// console.log(elementTop, "elementTop");
					// 计算元素顶部和底部距离容器顶部的最小距离
					const distance = Math.min(Math.abs(elementTop), Math.abs(elementBottom));
					// 如果当前元素距离更近，则更新最近的锚点
					if (distance < closestDistance) {
						closestDistance = distance;
						closestAnchor = key;
					}
				}
			});

			// 如果最近的锚点发生变化，则更新当前锚点
			if (closestAnchor !== currentAnchor) {
				setCurrentAnchor(closestAnchor);
			}
		};
		function findLastNonEmptyIdItem(arr) {
			let lastIndex = arr.length - 1;
			while (lastIndex >= 0) {
				if (arr[lastIndex] && arr[lastIndex][1]) {
					// console.log(arr[lastIndex][1], "arr[lastIndex]");
					setCurrentAnchor(arr[lastIndex][0]);
					return arr[lastIndex][0];
				}
				lastIndex--;
			}
			return null;
		}
		const debouncedHandleScroll = debounce(handleScroll, 100);

		containerRef.current?.addEventListener("scroll", debouncedHandleScroll);

		return () => {
			containerRef.current?.removeEventListener("scroll", debouncedHandleScroll);
		};
	}, [containerRef, anchorItemsRef]);

	const scrollToAnchor = key => {
		const el = anchorItemsRef.current[key] || document.getElementById(key);
		// console.log("scrollToAnchor", containerRef, el, key, anchorItemsRef);
		if (el) {
			// 留5px的距离，以防止锚点元素被遮挡
			containerRef.current.scrollTo({
				top:
					el.getBoundingClientRect().top + containerRef.current.scrollTop - containerRef.current.getBoundingClientRect().top - 5,
				behavior: "smooth"
			});
			setCurrentAnchor(key);
		}
	};

	return { currentAnchor, scrollToAnchor };
};
